import dayjs from "dayjs";
import { ref, reactive, onMounted, toRaw, h } from "vue";
import { isString, isEmpty } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import {
  useRouter,
  useRoute,
  type LocationQueryRaw,
  type RouteParamsRaw
} from "vue-router";

/** 弹窗依赖 */
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import orderForm from "../form/index.vue";

/** api接口请求 */
import { getOrderList } from "@/api/dashboard";

/** 获取当前时间 */
const today = dayjs().startOf("day").valueOf();

/** 表格 */
const useTable = timePeriod => {
  const { toDetail } = useDetail();
  // ⚙️状态初始化
  const formRef = ref();
  /** 是否处于 Loding 状态 */
  const loading = ref(true);
  /** 表格数据 */
  const dataList = ref([]);
  /** 翻页器定义 */
  const pagination = reactive({
    total: 0,
    pageSize: 15,
    currentPage: 1,
    background: true
  });

  /** 列配置 */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "订单编号",
      prop: "orderno",
      sortable: true,
      width: 90
    },
    {
      label: "时间",
      prop: "orderdate",
      sortable: true,
      minWidth: 130
    },
    {
      label: "单位名称",
      prop: "purchasingunit",
      minWidth: 130
    },
    {
      label: "收货人",
      prop: "contactsname",
      minWidth: 130
    },
    {
      label: "订单金额",
      prop: "price",
      sortable: true,
      minWidth: 130
    },
    {
      label: "订单状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row, props }) => {
        const { color, textColor } = getOrderTagProps(row.status);
        return (
          <el-tag
            size={props.size}
            color={color}
            style={{ color: textColor, border: `1px solid ${color}` }}
          >
            {row.status}
          </el-tag>
        );
      }
    },
    {
      label: "快递状态",
      prop: "logisticsstatus",
      minWidth: 90,
      cellRenderer: ({ row, props }) => {
        const { color, textColor } = getDeliveryTagProps(row.logisticsstatus);
        return (
          <el-tag
            size={props.size}
            color={color}
            style={{ color: textColor, border: `1px solid ${color}` }}
          >
            {row.logisticsstatus || "未发货"}
          </el-tag>
        );
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  /**
   * @description: 订单详情搜索方法
   * @param {Array} timePeriod 时间段列表
   */
  async function onSearch(timePeriod: Array<number>) {
    loading.value = true;
    let searchTime = toRaw(timePeriod);
    getOrderList({
      starttime: searchTime[0],
      endtime: searchTime[1],
      page: pagination.currentPage,
      size: pagination.pageSize
    }).then(res => {
      dataList.value = res.data.orderlist;
      pagination.total = res.data.total;
      loading.value = false;
      return res;
    });
  }

  async function defaultSearch(timePeriod: Array<number>) {
    pagination.currentPage = 1;
    onSearch(timePeriod);
  }

  /** 翻页器-改变页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch(timePeriod.value);
  }
  /** 翻页器-改变页数 */
  function handleCurrentChange(val) {
    pagination.currentPage = val;
    onSearch(timePeriod.value);
  }

  function openDialog() {
    addDialog({
      title: "查询订单详情",
      props: {
        formInline: {
          orderno: ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(orderForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as any;
        console.log(curData);
        FormRef.validate(valid => {
          if (valid) {
            done(); // 关闭弹框
            // router.push({
            //   name: "OrderDetail",
            //   query: { id: curData.orderno }
            // });
            toDetail({ id: curData.orderno }, "params");
          }
        });
      }
    });
  }
  type OrderStatus = "未发货" | "未开票" | "未回款" | "已回款";
  /** 获取订单状态标签样式 */
  const getOrderTagProps = (status: OrderStatus) => {
    switch (status) {
      case "未发货":
        return {
          color: "#fff5f4",
          textColor: "#e85f33"
        };
      case "未开票":
        return {
          color: "#e8f4ff",
          textColor: "#1e90ff"
        };
      case "未回款":
        return {
          color: "#d4f4e4",
          textColor: "#4caf50"
        };
      case "已回款":
        return {
          // color: "#fef6f6",
          color: "#f0f9eb",
          // textColor: "#ff6f6f"
          textColor: "#00b8a9"
        };
      default:
        return {
          color: "#f0f0f0",
          textColor: "#000"
        };
    }
  };

  enum DeliveryStatus {
    Empty = "",
    InProgress = "进行中",
    Completed = "已完成"
  }

  const getDeliveryTagProps = (status: DeliveryStatus) => {
    switch (status) {
      case DeliveryStatus.Empty:
        return {
          color: "#fff5f4",
          textColor: "#e85f33"
        };
      case DeliveryStatus.InProgress:
        return {
          color: "#ecf5ff",
          textColor: "#619eff"
        };
      case DeliveryStatus.Completed:
        return {
          color: "#f0f9eb",
          textColor: "#67c23a"
        };
      default:
        return {
          color: "#f0f0f0",
          textColor: "#000"
        };
    }
  };

  onMounted(() => {
    onSearch(timePeriod.value);
  });

  return {
    columns,
    formRef,
    loading,
    dataList,
    pagination,
    onSearch,
    openDialog,
    defaultSearch,
    handleSizeChange,
    handleCurrentChange
  };
};

/** 时间选择器 */
const useDatePicker = () => {
  /** 时间段 */
  const timePeriod = ref([
    dayjs().startOf("week").add(1, "day").valueOf() / 1000,
    today / 1000
  ]);

  /** 快捷选择 */
  const shortcuts = [
    {
      text: "本周",
      value: () => {
        const end = today;
        const start = dayjs().startOf("week").add(1, "day").valueOf();
        return [start, end];
      }
    },
    {
      text: "上周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      }
    },
    {
      text: "上个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      }
    },
    {
      text: "近三个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      }
    }
  ];

  return {
    timePeriod,
    shortcuts
  };
};

/** 跳转详情页方法 */
function useDetail() {
  const route = useRoute();
  const router = useRouter();
  const getParameter = isEmpty(route.params) ? route.query : route.params;

  function toDetail(
    parameter: LocationQueryRaw | RouteParamsRaw,
    model: "query" | "params"
  ) {
    Object.keys(parameter).forEach(param => {
      if (!isString(parameter[param])) {
        parameter[param] = parameter[param].toString();
      }
    });
    if (model === "query") {
      // 保存信息到标签页
      useMultiTagsStoreHook().handleTags("push", {
        path: `/tabs/query-detail`,
        name: "TabQueryDetail",
        query: parameter,
        meta: {
          title: {
            zh: `No.${parameter.id} - 详情信息`,
            en: `No.${parameter.id} - DetailInfo`
          },
          // 如果使用的是非国际化精简版title可以像下面这么写
          // title: `No.${index} - 详情信息`,
          // 最大打开标签数
          dynamicLevel: 3
        }
      });
      // 路由跳转
      router.push({ name: "TabQueryDetail", query: parameter });
    } else if (model === "params") {
      useMultiTagsStoreHook().handleTags("push", {
        path: `/dashboard/order/:id`,
        name: "OrderDetail",
        params: parameter,
        meta: {
          title: `订单 ${parameter.id}`
          // title: {
          //   zh: `No.${parameter.id} - 详情信息`,
          //   en: `No.${parameter.id} - DetailInfo`
          // }
          // 如果使用的是非国际化精简版title可以像下面这么写
          // title: `No.${index} - 详情信息`,
        }
      });
      router.push({ name: "OrderDetail", params: parameter });
    }
  }

  // 用于页面刷新，重新获取浏览器地址栏参数并保存到标签页
  const initToDetail = (model: "query" | "params") => {
    if (getParameter) toDetail(getParameter, model);
  };

  return { toDetail, initToDetail, getParameter, router, route };
}

export { useTable, useDatePicker, useDetail };
